import axios from 'axios'
import {baseUrl} from '../config/env'
import {JwtToken} from '../config/mUtils'
import qs from 'qs'
import Util from '@/utils/Util'
import 'whatwg-fetch'

const UNION_API_BASE_URL = 'https://h5.ganyinfo.com/borrowapi/'

// Add a request interceptor
axios.interceptors.request.use(
  (config) => {
    let token = JwtToken.get()
    config.headers = {
      ...config.headers,
      Authorization: `${token}`,
      'Content-Type': 'application/x-www-form-urlencoded'
    }
    return config
  },
  (error) => {
    if (parseInt(error.request.status) === 0) {
      Util.msg('网络错误，请稍后再试')
    }
    return Promise.reject(error)
  }
)

// Add a response interceptor
axios.interceptors.response.use(
  (response) => {
    let code = parseInt(response.data.code)
    if (parseInt(response.status) >= 500) {
      Util.msg('系统错误，请稍后再试')
    }
    if (code === 2) {
      Util.msg('您未登录或登录已过期', function () {
        location.href = '/login'
      })
    } else if (code !== 200) {
      Util.msg(response.data.msg)
    }
    return response
  },
  (error) => {
    // Do something with response error
    if (parseInt(error.request.status) === 0) {
      Util.msg('网络错误，请稍后再试')
    }
    return Promise.reject(error)
  }
)

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
    .json()
    .then(function (resp) {
      let code = parseInt(resp.code)
      if (code === 2) {
        Util.msg('您未登录或登录已过期', function () {
          location.href = '/login'
        })
      } else if (code === 0) {
        Util.msg(resp.msg)
      }
      return Promise.resolve(resp)
    })
  } else {
    var error = new Error(response.statusText)
    error.response = response
    Util.msg('网络错误，请稍后再试')
    throw error
  }
}

// 用户注册
export const home = () => {
  return axios.get(`${UNION_API_BASE_URL}frontend/finance/h5/home`, qs.stringify({}))
}

// 用户注册
export const pageProducts = (pageId, pageNum = 1, pageSize = 50) => {
  let query = `?pageId=${pageId}&pageNum=${pageNum}&pageSize=${pageSize}`
  return axios.get(`${UNION_API_BASE_URL}/frontend/finance/h5/page_product_info${query}`)
}

export const RecordOperation = (mobile, channel, infoType = 1) => {
  let token = JwtToken.get()
  let params = qs.stringify({
    mobile: mobile,
    channel: channel,
    infoType: infoType,
    platformType: 3,
    token: token
  })
  return axios.post(`${UNION_API_BASE_URL}/frontend/common/opr_record`, params)
}

// 用户注册
export const register = (password, mobile, captcha, agentId = '') => {
  let formData = new FormData()
  formData.append('mobile', mobile)
  formData.append('password', password)
  formData.append('captcha', captcha)
  if (agentId && agentId.length > 0) {
    formData.append('agent_id', agentId)
  }

  return fetch(`${baseUrl}/api/user/register`, {
    method: 'POST',
    body: formData
  })
  .then(checkStatus)
}

// 用户登录
export const login = (mobile, password, agentId) => {
  let formData = new FormData()
  formData.append('mobile', mobile)
  formData.append('password', password)
  formData.append('agent_id', agentId)

  return fetch(`${baseUrl}/api/login`, {
    method: 'POST',
    body: formData
  })
  .then(checkStatus)
}

// 验证码登录
export const quickLogin = (mobile, captcha, agentId) => {
  let formData = new FormData()
  formData.append('mobile', mobile)
  formData.append('agent_id', agentId)
  formData.append('captcha', captcha)

  return fetch(`${baseUrl}/api/quick-login`, {
    method: 'POST',
    body: formData
  })
  .then(checkStatus)
}

// 验证码登录并注册
export const loginRegister = (mobile, captcha, agentId) => {
  let formData = new FormData()
  formData.append('mobile', mobile)
  formData.append('agent_id', agentId)
  formData.append('captcha', captcha)

  return fetch(`${baseUrl}/api/login-register`, {
    method: 'POST',
    body: formData
  })
  .then(checkStatus)
}

// 获取验证码
export const captcha = (mobile, agentId) => {
  let formData = new FormData()
  formData.append('mobile', mobile)
  formData.append('agent_id', agentId)

  return fetch(`${baseUrl}/api/captcha`, {
    method: 'POST',
    body: formData
  })
  .then(checkStatus)
}

// 获取验证码
export const captchaQuickLogin = (mobile, agentId) => {
  let formData = new FormData()
  formData.append('mobile', mobile)
  formData.append('agent_id', agentId)

  return fetch(`${baseUrl}/api/captcha/quick-login`, {
    method: 'POST',
    body: formData
  })
  .then(checkStatus)
}

// 获取验证码
export const captchaForgotPass = (mobile, agentId) => {
  let formData = new FormData()
  formData.append('mobile', mobile)
  formData.append('agent_id', agentId)

  return fetch(`${baseUrl}/api/captcha/forgot-pass`, {
    method: 'POST',
    body: formData
  })
  .then(checkStatus)
}

// 抽奖
export const luckyDraw = () => {
  return axios.post(`${baseUrl}/api/market/lucky/draw`, qs.stringify({}))
}

// 获取奖品信息
export const luckyInfo = () => {
  return axios.post(`${baseUrl}/api/market/lucky/info`, qs.stringify({}))
}

// 获取奖品信息
export const financeProducts = () => {
  return axios.post(`${baseUrl}/api/finance/products`, qs.stringify({}))
}

// 获取用户信息
export const getUserInfo = () => {
  return axios.get(`${UNION_API_BASE_URL}/frontend/finance/h5/userinfo`, qs.stringify({}))
}

// 数据上报
export const visitorReport = (pageId, visitorType, productId = 0, deviceId = '') => {
  let params = {
    pageId,
    visitorType,
    deviceId,
    productId
  }
  return axios.post(`${UNION_API_BASE_URL}/frontend/finance/h5/visitor_report`, qs.stringify(params))
}

// 获取银行卡信息
export const getbankcards = () => {
  return axios.post(`${baseUrl}/kpay/api/bankcard/list`, qs.stringify({}))
}

// 认证授权
export const auth = (idcardNo, name, mobile) => {
  let params = {
    'mobile': mobile,
    'idcardNo': idcardNo,
    'name': name
  }
  return axios.post(`${baseUrl}/kpay/api/idcard/auth`, qs.stringify(params))
}

// 添加储蓄卡
export const adddeposit = (cardNo, bankName, branchName, mobile, bankNo) => {
  let params = {
    'mobile': mobile,
    'cardNo': cardNo,
    'bankName': bankName,
    'branchName': branchName,
    'bankNo': bankNo
  }
  return axios.post(`${baseUrl}/kpay/api/bankcard/addDeposit`, qs.stringify(params))
}

// 添加信用卡
export const addcreditcard = (cardNo, bankName, mobile) => {
  let params = {
    'mobile': mobile,
    'cardNo': cardNo,
    'bankName': bankName
  }
  return axios.post(`${baseUrl}/kpay/api/bankcard/addCredit`, qs.stringify(params))
}

// 删除银行卡
export const delcard = (cardId) => {
  return axios.post(`${baseUrl}/kpay/api/bankcard/del`, qs.stringify({'cardId': cardId}))
}

// 设置主卡
export const setprimarycard = (cardId) => {
  return axios.post(`${baseUrl}/kpay/api/bankcard/setPrimary`, qs.stringify({'cardId': cardId}))
}

// 根据卡号获取银行信息
export const getbankinfo = (cardNo) => {
  return axios.post(`${baseUrl}/kpay/api/bankcard/bankInfo`, qs.stringify({'cardNo': cardNo}))
}

// 关键字搜索支行
export const getBankList = (keyword) => {
  return axios.post(`${baseUrl}/kpay/api/bank/list`, qs.stringify({'name': keyword}))
}

// 获取取现记录
export const getcashhistory = (cardNo) => {
  return axios.post(`${baseUrl}/kpay/api/cash/getCashList`, qs.stringify({}))
}

// 取现记录详情
export const getcashdetail = (id) => {
  return axios.post(`${baseUrl}/kpay/api/cash/getCashDetail`, qs.stringify({'id': id}))
}

// 修改密码
export const forgotPassword = (password, captcha, mobile, agentId) => {
  let formData = new FormData()
  formData.append('mobile', mobile)
  formData.append('password', password)
  formData.append('captcha', captcha)
  formData.append('agent_id', agentId)

  return fetch(`${baseUrl}/api/forgot-pass`, {
    method: 'POST',
    body: formData
  })
  .then(checkStatus)
}

// 获取图片
export const getImage = (fileId) => {
  return axios.get(`${baseUrl}/kpay/api/image/show?fileId=${fileId}`, {responseType: 'blob'})
}

// 修改用户信息
export const modifyUser = (nickName = '', mobile = '', sex = '', avatar = '') => {
  let params = {}
  if (nickName) {
    params['nickName'] = nickName
  }
  if (mobile) {
    params['mobile'] = mobile
  }
  if (sex) {
    params['sex'] = sex
  }
  if (avatar) {
    params['avatar'] = avatar
  }
  return axios.post(`${baseUrl}/kpay/api/user/modify`, qs.stringify(params))
}

// 校验token
export const checkToken = () => {
  return axios.post(`${baseUrl}/kpay/api/checkToken`)
}

// 快捷取现接口（ajax请求）
export const quickPayRequest = (amount, cardId, enterCardId, cashback = 0) => {
  let params = {'cardId': cardId, 'amount': amount, 'enterCardId': enterCardId}
  if (/^[1-9]{1}[0-9]*(\.[0-9]+)?$/.test(cashback)) {
    params.cashback = cashback
  }
  return axios.post(`${baseUrl}/kpay/api/trade/quickPay/request2`, qs.stringify(params))
}

// 快捷取现接口（ajax请求）
export const authTakeCash = (uid) => {
  let formData = new FormData()
  formData.append('_s', uid)
  formData.append('ajax', 1)

  return fetch(`${baseUrl}/api/auth-take-cash`, {
    method: 'POST',
    body: formData
  })
  .then(checkStatus)
}
